#1 编码：str -> bytes
str1 = '伟大的中国梦'
str1_code = str1.encode(errors='replace')
print(str1_code) # 默认是utf-8，因为utf-8中文占三个字节
# b'\xe4\xbc\x9f\xe5\xa4\xa7\xe7\x9a\x84\xe4\xb8\xad\xe5\x9b\xbd\xe6\xa2\xa6'

str1_code1 = str1.encode('gbk', errors='replace')
print(str1_code1) # gbk中的中文占两个字节
# b'\xce\xb0\xb4\xf3\xb5\xc4\xd6\xd0\xb9\xfa\xc3\xce'

#2 编码中的出错问题
str2 = '耶☺'
#str2_code = str2.encode('gbk', errors='strict') #报错
str2_code = str2.encode('gbk', errors='ignore')
print(str2_code)
# b'\xd2\xae'
str2_code = str2.encode('gbk', errors='replace')
print(str2_code) # 将错误替换成 ?号
# b'\xd2\xae?'

#3 解码：bytes -> str
print(bytes.decode(str1_code,'utf-8'))
# 伟大的中国梦
print(bytes.decode(str1_code1,'gbk'))
# 伟大的中国梦